import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { useDebounceFn, useSetState } from 'ahooks';
import { Form, DatePicker, Select, Button, message, Popconfirm } from 'antd';
import * as echarts from 'echarts';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { CaretLeftOutlined, CaretRightOutlined, UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';

import { SERVER_URL_OBJ } from '@/../config/urlConfig';
import { PageLoading, TRDefault, TRCheckboxModal, DimensionalSort } from '@/components/index.js';
import { export_json_to_excel, exportGroup } from '@/utils/fileExport.js';
import { useRem } from '@/hooks/index.js';
import Pointer from '@/components/Pointer';

import {
  SELECT_DATA,
  OPTION_KEY,
  tableHead,
  operators,
  headerMap,
  UNIT_TYPE_OPTIONS,
} from './helper';
import BaseTable from './components/BaseTable';
import { ChartDealTariff, ChartDealIncome, ChartDealPrice } from './components/Charts/index.js';
import { queryUnitOptions, queryReanalyzeDataData, getDynamicColumns } from './services.js';
import { formatJson, pointConvert } from './utils.js';

const { RangePicker } = DatePicker;
const monthFormat = 'YYYYMMDD';
const { CLIENT_ENV } = process.env;
let dataInit: moment.Moment[] = [];
// 当前日期大于当前月的2号
if (moment().diff(moment().startOf('month'), 'days') > 1) {
  dataInit = [moment().startOf('month'), moment()];
} else {
  dataInit = [
    moment().subtract(1, 'months').startOf('month'),
    moment().subtract(1, 'months').endOf('month'),
  ];
}

const MyStations = (props: any) => {
  const { value = [], onChange, treeData = [], optionAll = [], className } = props;
  const title = '交易单元';
  const isEmpty = !treeData.length;
  useEffect(() => {
    if (!value.length) {
      onChange(optionAll);
    }
  }, [optionAll]);
  const onHandleModal = async () => {
    if (isEmpty) return;
    const result = await TRCheckboxModal.show({
      title,
      value,
      treeData,
    });
    if (result?.index === 1 && result.checkedKeys.length) {
      onChange(result.checkedKeys);
    }
    TRCheckboxModal.dismiss();
  };
  return (
    <div className={`${!value.length ? styles.jydy_select : ''} ${className} `}>
      <Select
        open={false}
        style={{
          width: 200,
        }}
        value={
          !value.length
            ? '请选择交易单元'
            : value.length === optionAll.length
            ? '全部'
            : `${value.length}项/${optionAll.length}项`
        }
        onClick={onHandleModal}
        onChange={onChange}
      />
    </div>
  );
};

const PowerForecastAdjusted = ({ menuCode, buttonPermissions }: any) => {
  const [loading, setLoading] = useState(false),
    [listLoading, setListLoading] = useState(false),
    [columns, setColumns] = useState([]),
    [tableData, setTableData] = useState({}),
    [tableDataSource, setTableDataSource] = useState([]), //主表格数据
    [tableHeader, setTableHeader]: any = useState(), //表头
    [stations, setStations] = useState<any>([]), // 全部场站（平铺）
    [regionsStations, setRegionsStations] = useState([]), // 对应省份场站（平铺）
    [stationTree, setStationTree] = useState<any>([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState<any>([]), //所选省份全部场站(全选)
    [param, setParam] = useState(SELECT_DATA), //灵活聚合项
    [form] = Form.useForm(),
    reSize = useRem(1920),
    [echartsTariffData, setEchartsTariffData] = useState<any>({}), //偏差电费组成
    [echartsIncomeData, setEchartsIncomeData] = useState<any>({}), //综合扣费收入
    [echartsPriceData, setEchartsPriceData] = useState<any>({}), //综合扣费电价
    [echartsParam, setEchartsParam]: any = useState(), //图表筛选参数
    [dates, setDates] = useState(null),
    [filterUnitOptions, setFilterUnitOptions] = useState(), //父维度筛选 交易单元列表
    [dateTime, setDateTime] = useState<any>(), //父维度筛选 时间
    [regions, setRegions] = useState<any[]>([]), // 全部省份
    [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false), // 是否为图表全屏展示
    [isFullScreenTable, setIsFullScreenTable] = useState(false), // 是否为表格全屏展示
    [indicatorSummary, setIndicatorSummary] = useState<any>([]),
    [visible, setVisible] = useState(false), // 控制大数据查询前提示
    [exportParam, setExportParam] = useSetState({
      dateRange: [],
    }),
    [state, setState] = useSetState<any>({
      refData: [],
    }),
    [regionCode, setRegionCode] = useState<any>('');

  useEffect(() => {
    init();
  }, []);

  /** handle data */
  async function init() {
    // 获取数据权限
    setLoading(true);
    const res = await queryUnitOptions({ menuCode }).catch(() => setLoading(false));
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      initDataPower(res?.data);
    }
  }

  //获取省份对应交易单元
  const getStationOptions = (data: any) => {
    const _stationTree: any = [],
      _optionAll: any = [];
    const _groups = _.groupBy(data, '_companyName');
    for (const key in _groups) {
      // 有交易单元的集团
      _stationTree.push({
        title: key,
        key: Math.random(),
        children: _groups[key].map((item: any) => {
          _optionAll.push(item._stationCode);
          return {
            title: item._stationName,
            key: item._stationCode,
          };
        }),
      });
    }
    setOptionAll(_optionAll);
    setStationTree(_stationTree);
  };

  //切换省份
  const onRegionChange = (value: any, selectOptions: any) => {
    setRegionCode(selectOptions._regionCode);
    form.setFieldsValue({
      unit: [],
      unitType: 0,
    });
    const _stations = stations.filter((x: any) => value.includes(x._regionName));
    setEchartsParam({
      ...echartsParam,
      unitType: 0,
    });
    setRegionsStations(_stations);
    getStationOptions(_stations);
  };

  useEffect(() => {
    if (stations?.length) {
      const regionName = form.getFieldValue('region') ?? '';
      onRegionChange(regionName, { label: regionName, value: regionName, _regionCode: regionCode });
    }
  }, [stations]);

  const _onFinish = useDebounceFn(
    (values: any) => {
      setExportParam({
        dateRange: values.date,
      });
      // 查询
      const _formData: any = values,
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _pointNum = _formData.point,
        _tag = _formData.tag,
        _unit = _formData.unit,
        _param = [SELECT_DATA[0], SELECT_DATA[1]];
      setParam(_param); //初始化聚合维度
      _fetchFile({
        cacheable: true,
        needTotal: true,
        newWay: true,
        newOperators: operators,
        order: _param,
        param: JSON.stringify({
          menuCode,
          regionCode,
          stationIdList: _unit,
          dataTimeOrderType: _pointNum === '24' ? 'TWENTY_FOUR' : 'NINETY_SIX',
          startDate: _startDate,
          endDate: _endDate,
          reanalyzeDataType: _tag === '1' ? 'CS' : 'JS',
        }),
        url: `${
          SERVER_URL_OBJ[`${CLIENT_ENV === 'dev' ? 'test' : CLIENT_ENV}` || 'release']
        }/reanalyze/electricityRateAnalysis/electricityRateAnalysisData`,
      });
    },
    { wait: 500 },
  );
  //默认请求
  const defaultRequest = (_stations: any, _regions: any) => {
    const stationsIds = _stations
      .filter((item: any) => item._regionName == _regions[0].label)
      ?.map((item: any) => item?.value || '');
    form.setFieldsValue({ region: _regions[0].label, unit: [] });
    getStationOptions(_stations.filter((x: any) => x._regionName === _regions?.[0]?.label));
    const values = {
      date: dataInit,
      point: '96',
      unitType: 0,
      tag: '2',
      unit: stationsIds,
    };
    setEchartsParam({
      ...values,
      timeOrder: '96',
    });
    //重新渲染表格数据
    _onFinish.run(values);
  };
  function initDataPower(data = [] as any) {
    // 处理数据权限
    if (!data) {
      // setErrorMsg('暂无数据权限');
      return;
    }
    const _stations = [] as any;
    const _rs = [] as any;
    data.map((x: any) => {
      // 省份
      _rs.push({
        _regionCode: x.value,
        label: x.label,
        value: x.label,
      });
      (x?.children || []).map((y: any) => {
        // 公司
        (y?.children || []).map((z: any) => {
          // 场站
          const temp = {
            _regionCode: x.value,
            _regionName: x.label,
            _companyCode: y.value,
            _companyName: y.label,
            _stationCode: z.value,
            _stationName: z.label,
            label: z.label,
            value: z.value,
            type: z.type,
          };
          _stations.push(temp);
        });
      });
    });
    setRegionCode(_rs?.[0]?._regionCode || '');
    setRegions(_rs);
    setStations(_stations);
    defaultRequest(_stations, _rs);
  }

  const onTypeChange = (val: any) => {
    const arr = [];
    const _groups = _.groupBy(regionsStations, '_companyName');
    for (const key in _groups) {
      const _newGroup = [];
      for (const k in _groups[key]) {
        if (!val) {
          // 全部交易单元
          _newGroup.push(_groups[key][k]);
        }
        if (_groups[key][k].type === val) {
          // 选中的交易单元
          _newGroup.push(_groups[key][k]);
        }
      }
      if (_newGroup.length) {
        // 有交易单元的集团
        arr.push({
          title: key,
          key: Math.random(),
          children: _newGroup.map((item) => ({
            title: item._stationName,
            key: item._stationCode,
          })),
        });
      }
    }
    setStationTree(arr);
  };
  //取出非合计行默认第一行 最后一个子维度 作为echarts的横坐标
  const _getXAXIS = (data: any, arr: any[]) => {
    const _temp: any[] = [];
    const recursion = (item: any, index: number): any[] => {
      _temp.push({
        tag: item[0]?.tag,
        title: item[0]?.title,
      });
      if (item[0]?.children instanceof Array && item.length > 0) {
        return recursion(item[0].children, index - 1);
      }
      return _temp;
    };
    return recursion(data, arr.length - 1);
  };

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenEcharts) {
      classNameEcharts = `${styles.chartsFullWidth}`;
      classNameTable = `${styles.tableNoWidth}`;
    } else if (isFullScreenTable) {
      classNameEcharts = `${styles.chartsNoWidth}`;
      classNameTable = `${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form && form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = (newVisible?: boolean) => {
    const { date, unit } = form.getFieldsValue();
    if (date && unit.length > 0) {
      const days = date[1].diff(date[0], 'days') + 1;
      if (days * unit.length > 900) {
        setVisible(!!newVisible);
      } else {
        confirm.run();
      }
    } else if (!date || !unit.length) {
      setVisible(false);
    } else {
      confirm.run();
    }
  };
  /**建立echarts链接 */
  const getRef: any = (refData: any) => {
    const arr = [...state.refData];
    state.refData.push(refData);
    arr.push(refData);
    if (arr.length >= 2) {
      echarts.connect([...arr]);
    }
    setState({
      refData: arr,
    });
  };
  //根据父维度 筛选出图表所需数据  return:最后一个维度数组
  const _getFilterXAXIS = (data: any, arr: any[]): any[] => {
    const _echartsParam = _.cloneDeep(echartsParam);
    //取最后一个维度 第一行数据
    const recursion = (item: any, index: number): any[] => {
      const _item: any[] = [];
      item.forEach((t: any) => {
        if (t.title === '合计') return;
        _item.push(t);
      });
      let _temp: any[] = [];
      //如果已经是最后一个维度
      if (arr.length - 1 <= index) {
        return _item;
      }
      _item.forEach((t: any) => {
        t.title === _echartsParam[OPTION_KEY[arr[index]]] &&
          (_temp = recursion(t.children, index + 1));
      });
      return _temp;
    };
    return recursion(data, 0);
  };
  //获取默认第一行 根据传入维度递归获取数据
  const _getDimensionData = (data: any, deepIndex: number): any[] => {
    if (deepIndex) {
      return _getDimensionData(
        data[0].children.length ? data[0].children : data[1].children,
        deepIndex - 1,
      );
    }
    return data;
  };
  //dealFunc
  const dealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title:
        tag === '时点'
          ? pointConvert(title, form)
          : tag === '日期'
          ? title.replaceAll('-', '')
          : title,
      tag: tag,
    };

    meta.forEach((_t: string, _i: number) => {
      obj[headerMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    });

    // //计量电量
    // const s1 = obj.mediumAndLongQuantity;
    // //中长期电量*0.85
    // const s2 = obj.spotGoodsQuantity * 0.85;
    // //电能电费/计量电量
    // const p1 = obj.comprehensiveElectricityBill / obj.spotGoodsQuantity;
    // //中长期电价*1.1
    // const p2 = obj.mediumAndLongElectrovalence * 1.1;

    // const isNaN = s1 < s2 && p1 > p2;
    // obj.recoveries = isNaN ? '-' : obj.recoveries;
    // obj.compensationExpenses = isNaN ? '-' : obj.compensationExpenses;
    return obj;
  };
  //dealFunc
  const totalDealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title: title,
      tag: tag,
    };
    meta.forEach((_t: string, _i: number) => {
      obj[headerMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    });
    obj.children = [];
    return obj;
  };
  //处理表格数据 dataSource表格数据 postdata选项
  const getNewDataSource = (dataSource: any, order: any, selectedKeys: string[] = []) => {
    if (!dataSource) return [];
    const formatForTable = (item: any, optionName: any, index = 0) => {
      const arr: any[] = [];
      Object.entries(item).map((t: any) => {
        if (t[0] === 'total') {
          return;
        }
        //最后一个维度为数组
        if (t[1] instanceof Array) {
          arr.push(dealFunc(optionName[index], dataSource.meta, t[0], t[1]));
          return;
        }
        const obj = dealFunc(optionName[index], dataSource.meta, t[0], t[1].total);
        obj.children = formatForTable(t[1], optionName, index + 1);
        arr.push(obj);
      });
      arr.sort((a: any, b: any) => {
        if (optionName[index] === '交易单元') {
          return a.title.localeCompare(b.title, 'zh-CN');
        }
        //默认时点排序方式
        return a.title > b.title ? 1 : -1;
      });
      return arr;
    };
    // 添加合计行
    const result = [
      totalDealFunc(order[0], dataSource.meta, '合计', dataSource.data.total),
      ...formatForTable(dataSource.data, order),
    ];

    const _total = result[0],
      indicatorSummaryEnum = [
        {
          title: '综合结算',
          beforeUnit: 'MWh',
          afterUnit: '元/MWh',
          countUnit: '万元',
          beforeList: ['synthesizeQuantity'],
          afterList: ['synthesizeElectrovalence'],
          countList: ['comprehensiveIncome'],
        },
        {
          title: '中长期',
          beforeUnit: 'MWh',
          afterUnit: '元/MWh',
          countUnit: '万元',
          beforeList: ['mediumAndLongQuantity'],
          afterList: ['mediumAndLongElectrovalence'],
          countList: ['mediumAndLongPower'],
        },
        {
          title: '现货',
          beforeUnit: 'MWh',
          afterUnit: '元/MWh',
          countUnit: '万元',
          beforeList: ['spotGoodsQuantity'],
          afterList: ['spotGoodsElectrovalence'],
          countList: ['spotGoodsPower'],
        },
      ];
    const indicatorSummaryList: any = [];
    indicatorSummaryEnum?.forEach((ise, index) => {
      const indicatorSlide = {
        ...ise,
        name: ise.title,
      };
      const isContainList = [],
        isBeforeList: any = [],
        isCountList: any = [],
        isAfterList: any = [];
      let beforeSum = 0,
        countSum = 0,
        afterSum = 0;
      ise.beforeList?.forEach((c) => {
        if (selectedKeys.includes(c)) {
          isContainList.push(c);
          isBeforeList.push(c);
        }
      });
      ise.afterList?.forEach((c) => {
        if (selectedKeys.includes(c)) {
          isContainList.push(c);
          isAfterList.push(c);
        }
      });
      ise.countList?.forEach((c) => {
        if (selectedKeys.includes(c)) {
          isContainList.push(c);
          isCountList.push(c);
        }
      });
      if (!isContainList?.length) return;
      if (isBeforeList?.length) {
        isBeforeList?.forEach((b: any) => {
          beforeSum += parseFloat(_total[b]);
        });
        indicatorSlide.before = beforeSum.toFixed(3);
      }
      if (isAfterList?.length) {
        isAfterList?.forEach((b: any) => {
          afterSum += parseFloat(_total[b]);
        });
        indicatorSlide.after = afterSum.toFixed(2);
      }
      if (isCountList?.length) {
        isCountList?.forEach((b: any) => {
          countSum += parseFloat(_total[b]);
        });
        indicatorSlide.count = (countSum / 10000).toFixed(4);
      }
      indicatorSummaryList.push(indicatorSlide);
    });

    //总览综合电费、电价前端重新计算
    const _count = result.reduce((a, b, i) => {
      if (!i) return 0;
      return parseFloat(a) + parseFloat(b.comprehensiveIncome);
    }, 0);
    indicatorSummaryList[0] = {
      ...indicatorSummaryList[0],
      count: (_count / 10000).toFixed(4),
      after: (parseFloat(_count) / parseFloat(indicatorSummaryList[0].before)).toFixed(2),
    };
    setIndicatorSummary(indicatorSummaryList);
    return result;
  };
  const flattenDeep = (list: any = [], selectedKeys: string[] = []) => {
    list?.forEach((l: any) => {
      // 默认选中
      if (l?.checkbox === 1 && l?.key) {
        selectedKeys.push(l.key);
      }
      l?.children?.length && flattenDeep(l.children, selectedKeys);
    });
    return selectedKeys;
  };

  //根据筛选参数 重绘图表
  const repaint = (arr) => {
    const _echarsData = _getFilterXAXIS(tableDataSource, param);
    const _xaxis = _echarsData.map((t) => t.title);
    const list = _.cloneDeep(arr || tableHeader);

    setEchartsTariffData({
      XAXIS: _xaxis,
      ...(list?.filter((thv: any) => thv.field === 'synthesizeQuantity')?.length
        ? {
            synthesizeQuantity: _echarsData.map((t) => t.synthesizeQuantity),
          }
        : {}),
      ...(list?.filter((thv: any) => thv.field === 'synthesizeElectrovalence')?.length
        ? {
            synthesizeElectrovalence: _echarsData.map((t) => t.synthesizeElectrovalence),
          }
        : {}),
    });
    setEchartsIncomeData({
      XAXIS: _xaxis,
      ...(list?.filter((thv: any) => thv.field === 'mediumAndLongQuantity')?.length
        ? {
            mediumAndLongQuantity: _echarsData.map((t) => t.mediumAndLongQuantity),
          }
        : {}),
      ...(list?.filter((thv: any) => thv.field === 'spotGoodsQuantity')?.length
        ? {
            spotGoodsQuantity: _echarsData.map((t) => t.spotGoodsQuantity),
          }
        : {}),
    });
    setEchartsPriceData({
      XAXIS: _xaxis,
      ...(list?.filter((thv: any) => thv.field === 'synthesizeElectrovalence')?.length
        ? {
            synthesizeElectrovalence: _echarsData.map((t) => t.synthesizeElectrovalence),
          }
        : {}),
      ...(list?.filter((thv: any) => thv.field === 'mediumAndLongElectrovalence')?.length
        ? {
            mediumAndLongElectrovalence: _echarsData.map((t) => t.mediumAndLongElectrovalence),
          }
        : {}),
      ...(list?.filter((thv: any) => thv.field === 'wholeNetworkElectrovalence')?.length
        ? {
            wholeNetworkElectrovalence: _echarsData.map((t) => t.wholeNetworkElectrovalence),
          }
        : {}),
      ...(list?.filter((thv: any) => thv.field === 'spotGoodsElectrovalence')?.length
        ? {
            spotGoodsElectrovalence: _echarsData.map((t) => t.spotGoodsElectrovalence),
          }
        : {}),
    });
  };

  const filterColumns = (list: string[] = []) => {
    const headerList: any = [];
    tableHead?.forEach((t) => {
      if (list?.includes(t?.field)) {
        headerList.push(t);
      }
    });
    if (Object.keys(tableData)?.length) {
      getNewDataSource(tableData, param, list);
    }
    setTableHeader(headerList);
    repaint(headerList);
  };
  //请求表格数据
  async function _fetchFile(postdata: any) {
    setListLoading(true);
    setTableDataSource([]);
    const res = await queryReanalyzeDataData(postdata).catch(() => {});
    const columnsRes = await getDynamicColumns({
      regionCode,
      menuCode,
    });
    setListLoading(false);
    if (res.statusCode === HttpCode.SUCCESS) {
      let selectedKeys: any = [];
      selectedKeys = flattenDeep(columnsRes?.data || [], selectedKeys);
      filterColumns(selectedKeys);
      setTableData(res?.data || {});
      const data: any = getNewDataSource(res?.data, postdata.order, selectedKeys);
      setTableDataSource(data);
      setColumns(columnsRes?.data || []);
      if (data.length) {
        const _data = _.cloneDeep(data);
        //设置图表数据
        const _echartsData = _getXAXIS(_data.splice(1), SELECT_DATA);
        //设置父维度列表值
        setFilterUnitOptions(
          (form.getFieldValue('unit')?.length ? form.getFieldValue('unit') : optionAll).map(
            (t: any) => {
              const item = stations.find((_t: any) => t == _t._stationCode);
              return {
                label: item._stationName,
                value: item._stationName,
              };
            },
          ),
        );
        setDateTime(form.getFieldValue('date'));
        //设置父维度选择默认值【合约量价图】默认：第一个维度
        setEchartsParam({
          date:
            postdata.order.includes('日期') &&
            moment(_echartsData.find((t) => t.tag === '日期').title).format('YYYYMMDD'),
          unit:
            postdata.order.includes('交易单元') &&
            _echartsData.find((t) => t.tag === '交易单元').title + '',
          timeOrder:
            postdata.order.includes('时点') && form.getFieldValue('point') === '24'
              ? '0100'
              : '0015',
        });
      }
    }
  }
  const onexport = () => {
    if (!tableDataSource.length) return;
    const _tableDataSource = _.cloneDeep(tableDataSource.splice(1));
    const hasSave =
      buttonPermissions.filter((item: any) => item.menuCode === 'electricityCostAnalysisExport')
        .length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const _date = exportParam.dateRange;
    const filename = `电费分析-${moment(_date[0]).format('YYYYMMDD')}_${moment(_date[1]).format(
      'YYYYMMDD',
    )}`;
    const exportColumns = [
      {
        header: '',
        key: 'title',
      },
    ];
    tableHead.forEach((xc) => {
      exportColumns.push({
        header: xc.name,
        key: xc.field,
      });
    });
    exportGroup(_tableDataSource, exportColumns, filename);
    return;
    const params: any = {
      multiHeader: [],
      header: [''],
      data: [],
      merges: [
        'B1:D1',
        'E1:H1',
        'I1:K1',
        'A3:A2',
        'B3:B2',
        'C3:C2',
        'D3:D2',
        'E3:E2',
        'F3:F2',
        'G3:G2',
        'H3:H2',
        'I3:I2',
        'J3:J2',
        'K3:K2',
      ],
      filename,
    };
    const data = tableDataSource;
    const dataFalt: any[] = [];
    data.map((x: any) => {
      dataFalt.push(x);
      (x?.children || []).map((y: any) => {
        dataFalt.push(y);
        (y?.children || []).map((z: any) => {
          dataFalt.push(z);
          (z?.children || []).map((e: any) => {
            dataFalt.push(e);
          });
        });
      });
    });
    const filterVal: string[] = ['title'];
    const multiHeader2 = [param[0]],
      multiHeader = [''];
    tableHeader?.forEach((item: any) => {
      //第一级
      multiHeader.push(params.multiHeader.includes(item.parentName) ? '' : item.parentName);
      //第二级
      multiHeader2.push(
        item.secondParentName
          ? item.secondParentName === multiHeader2[multiHeader2.length - 1]
            ? ''
            : item.secondParentName || ''
          : item.name,
      );
      //最后一级
      params.header.push(item.name);
      filterVal.push(item.field);
    });
    params.multiHeader = [multiHeader, multiHeader2];
    params.data = formatJson(filterVal, dataFalt);
    export_json_to_excel(params);
  };

  useEffect(() => {
    if (tableDataSource.length > 0) {
      repaint();
    }
  }, [echartsParam]);
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      const regionName = form.getFieldValue('region') ?? '';
      onRegionChange(regionName, {
        label: regionName,
        value: regionName,
        _regionCode: regions?.[0]?._regionCode || '',
      });
      setTableDataSource([]);
      defaultRequest(stations, regions);
    },
    { wait: 500 },
  );
  const onOpenChange = (open: boolean) => {
    if (open) {
      setDates([null, null]);
    } else {
      setDates(null);
    }
  };
  const _renderHeader = () => {
    const initialValues = () => {
      return {
        region: regions[0]?.label || '山西电力交易中心',
        date: dataInit,
        unitType: 0,
        point: '96',
        tag: '2',
      };
    };
    return (
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
        >
          <Form.Item name="region" className={styles.cell_item}>
            <Select
              options={regions}
              style={{ width: 200 }}
              placeholder="请选择省份"
              showSearch={true}
              filterOption={(input: any, option: any) => {
                return (option?.label).toLowerCase().includes(input.toLowerCase());
              }}
              onChange={(e, e2) => {
                onRegionChange(e, e2);
              }}
            />
          </Form.Item>
          <Form.Item
            name="unitType"
            rules={[{ required: true, message: '交易单元类型不可为空!' }]}
            className={styles.cell_item}
          >
            <Select
              options={UNIT_TYPE_OPTIONS}
              style={{ width: 80 }}
              placeholder="交易单元类型"
              onChange={(e) => {
                onTypeChange(e);
                form.setFieldsValue({ unit: [] });
              }}
            />
          </Form.Item>
          <Form.Item name="unit" className={styles.cell_item}>
            <MyStations options={stations} treeData={stationTree} optionAll={optionAll} />
          </Form.Item>
          <Form.Item
            name="date"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <React.Fragment>
              <RangePicker
                className={styles.select_date}
                format={'YYYYMMDD'}
                separator={'-'}
                value={dates || form.getFieldValue('date')}
                onOpenChange={onOpenChange}
                onChange={(val) => {
                  setExportParam({
                    dateRange: val,
                  });
                  form.setFieldsValue({ date: val });
                }}
                onCalendarChange={(val) => setDates(val)}
              />
            </React.Fragment>
          </Form.Item>
          <Form.Item name="point" className={styles.cell_item}>
            <div className={styles.tag}>
              <Pointer
                options={[
                  { label: '24', value: '24' },
                  { label: '96', value: '96' },
                ]}
                data={'96'}
              />
            </div>
          </Form.Item>
          <Form.Item name="tag" className={styles.cell_item}>
            <div className={styles.tag}>
              <Pointer
                options={[
                  { label: '测算数据', value: '1' },
                  { label: '结算数据', value: '2' },
                ]}
                data={'2'}
              />
            </div>
          </Form.Item>
          <Popconfirm
            title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
            visible={visible}
            onVisibleChange={handleVisibleChange}
            onConfirm={() => confirm.run()}
            onCancel={() => setVisible(false)}
            okText="确认"
            cancelText="取消"
          >
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
          </Popconfirm>
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
          <div
            className={`${styles.import} ${!tableDataSource.length && styles.disabled}`}
            onClick={onexport}
          >
            <UploadOutlined style={{ fontSize: '0.12rem' }} />
            导出
          </div>
        </Form>
      </div>
    );
  };
  //展板
  const _renderBoard = () => {
    if (!tableDataSource.length) return;
    return (
      <div className={styles.board}>
        {indicatorSummary
          ?.filter((v: any) => v.name !== '现货收入')
          ?.map((t: any, i: number) => {
            return (
              <div className={styles.item} key={i}>
                <div className={styles.right}>
                  <p className={styles.title}>{t.name}</p>
                  {t.count ? (
                    <>
                      <p className={styles.tip}>电费</p>
                      <span className={styles.price}>
                        {t.count < 0 ? '' : '+'}
                        {t.count}
                      </span>
                      <span className={styles.unit}>{t.countUnit}</span>
                    </>
                  ) : null}
                </div>
                <div className={styles.left}>
                  {t.before ? (
                    <React.Fragment>
                      <p className={styles.label}>电量</p>
                      <p className={styles.price}>
                        {t.before}
                        <span className={styles.price_unit}>{t.beforeUnit}</span>
                      </p>
                    </React.Fragment>
                  ) : null}
                  {t.after ? (
                    <React.Fragment>
                      <p className={styles.label} style={{ color: '#CEE3CB' }}>
                        电价
                      </p>
                      <p className={styles.price} style={{ color: '#CEE3CB' }}>
                        {t.after}
                        <span className={styles.price_unit}>{t.afterUnit}</span>
                      </p>
                    </React.Fragment>
                  ) : null}
                </div>
              </div>
            );
          })}
      </div>
    );
  };
  //表格图表内容区域渲染
  const _renderContent = () => {
    if (listLoading)
      return (
        <div className={styles.emty}>
          <PageLoading />
        </div>
      );
    if (!tableDataSource.length) return <TRDefault type={'empty'} />;
    /*获取设置选择器下拉列表项*/
    const pointOptions =
      param.includes('时点') && param.indexOf('时点') < param.length - 1
        ? _getDimensionData(tableDataSource, param.indexOf('时点')).map((t) => ({
            label: t.title,
            value: t.title,
          }))
        : [];
    //重新聚合
    const _polymerize = (options: any) => {
      setParam(options);
      //重新渲染表格数据
      const _formData: any = form.getFieldsValue(true),
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _pointNum = _formData.point,
        _tag = _formData.tag,
        _unit = _formData.unit;
      _fetchFile({
        cacheable: true,
        needTotal: true,
        newWay: true,
        newOperators: operators,
        order: options,
        param: JSON.stringify({
          menuCode,
          regionCode,
          stationIdList: _unit,
          dataTimeOrderType: _pointNum === '24' ? 'TWENTY_FOUR' : 'NINETY_SIX',
          startDate: _startDate,
          endDate: _endDate,
          reanalyzeDataType: _tag === '1' ? 'CS' : 'JS',
        }),
        url: `${
          SERVER_URL_OBJ[`${CLIENT_ENV === 'dev' ? 'test' : CLIENT_ENV}` || 'relpase']
        }/reanalyze/electricityRateAnalysis/electricityRateAnalysisData`,
      });
    };
    const _selectUnitOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        unit: value,
      });
    };
    const _selectDateOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        date: value.format('YYYYMMDD'),
      });
    };
    const _selectPointOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        timeOrder: value,
      });
    };
    //控制日历可选范围
    const disabledDate = (current: any) => {
      const _date = dateTime;
      return (current && current < _date[0].startOf('day')) || current > _date[1].endOf('day');
    };
    return (
      <>
        <div className={[styles.leftBox, getClassName().classNameTable].join(' ')}>
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
          <DimensionalSort
            reSize={reSize}
            optionsArray={SELECT_DATA}
            option={param}
            onClick={_polymerize}
            columns={columns}
            menuCode={menuCode}
            regionCode={regionCode}
            filterColumns={filterColumns}
          />
          <BaseTable tableData={tableDataSource} tableHeader={tableHeader} text={param[0]} />
        </div>
        <div className={[styles.rightBox, getClassName().classNameEcharts].join(' ')}>
          <div className={styles.filter_group}>
            <div className={styles.flex}>
              {param.map((t: any, i: number) => {
                if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_unit}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        showSearch
                        placeholder="选择交易单元"
                        onChange={_selectUnitOnChange}
                        value={echartsParam.unit}
                        options={filterUnitOptions}
                        filterOption={(input, option) => {
                          return (option?.label as unknown as string)
                            .toLowerCase()
                            .includes(input.toLowerCase());
                        }}
                      />
                    );
                  }
                }
                if (t === '日期' && param[param.length - 1] !== '日期') {
                  {
                    return (
                      <DatePicker
                        key={i}
                        onChange={_selectDateOnChange}
                        inputReadOnly
                        allowClear={false}
                        className={styles.filter_date}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        value={moment(echartsParam.date)}
                        format={monthFormat}
                        disabledDate={disabledDate}
                      />
                    );
                  }
                }
                if (t === '时点' && param[param.length - 1] !== '时点') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_point}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        placeholder="选择时点"
                        onChange={_selectPointOnChange}
                        value={echartsParam.timeOrder}
                        options={pointOptions}
                      />
                    );
                  }
                }
              })}
            </div>
          </div>
          <div className={styles.content_box}>
            <div
              className={styles.rightArrow}
              onClick={() => {
                setIsFullScreenEcharts(!isFullScreenEcharts);
              }}
            >
              {isFullScreenEcharts ? <CaretRightOutlined /> : <CaretLeftOutlined />}
            </div>
            {!echartsTariffData?.XAXIS?.length ||
            (Object.keys(echartsTariffData).length === 1 &&
              Object.keys(echartsIncomeData).length === 1 &&
              Object.keys(echartsPriceData).length === 1) ? (
              <TRDefault type="emptysm" />
            ) : (
              <>
                {Object.keys(echartsTariffData)?.length > 1 ? (
                  <>
                    <div className={styles.title} style={{ paddingTop: 0 }}>
                      场站总览
                    </div>
                    <div style={{ flex: 1 }}>
                      <ChartDealTariff
                        data={echartsTariffData}
                        scale={reSize / 100}
                        getRef={getRef}
                      />
                    </div>
                  </>
                ) : null}
                {Object.keys(echartsIncomeData)?.length > 1 ? (
                  <>
                    <div className={styles.title}>电量分析</div>
                    <div style={{ flex: 1 }}>
                      <ChartDealIncome
                        data={echartsIncomeData}
                        scale={reSize / 100}
                        getRef={getRef}
                      />
                    </div>
                  </>
                ) : null}
                {Object.keys(echartsPriceData)?.length > 1 ? (
                  <>
                    <div className={styles.title}>电价分析</div>
                    <div style={{ flex: 1 }}>
                      <ChartDealPrice
                        data={echartsPriceData}
                        scale={reSize / 100}
                        getRef={getRef}
                      />
                    </div>
                  </>
                ) : null}
              </>
            )}
          </div>
        </div>
      </>
    );
  };
  if (loading) return <PageLoading />;
  return (
    <>
      {_renderHeader()}
      {_renderBoard()}
      <div className={styles.content_body}>
        <div className={styles.content}> {_renderContent()}</div>
      </div>
    </>
  );
};
export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(PowerForecastAdjusted);
